<?php

declare (strict_types = 1);

namespace app\matter\controller;

use app\matter\BaseController;
use app\matter\model\UnitModel;
use think\facade\Db;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

//单位管理
class Unit extends BaseController
{
    //首页
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['keywords'])) {
                $where[] = ['name|full_name', 'like', '%' . $param['keywords'] . '%'];
            }
            $area = array_column(get_area($this->area_id),'id');
            $where[] = ['area_id', 'in', $area];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = UnitModel::with('area')->where($where)->paginate($rows, false, ['query' => $param]);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    // 新增/编辑
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                //修改
                $Model = UnitModel::find($id);
                $Model->save($param);
                add_log('edit', $param['id'], $param);
            } else {
                //新增
                $Model = new UnitModel();
                $param['uid'] = $this->uid;
                $Model->save($param);
                add_log('add', $Model->id, $param);
            }
            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = UnitModel::find($id);
                View::assign('detail', $detail);
            }
            View::assign('id', $id);
            $area_list = set_recursion2(get_area($this->area_id));
            View::assign('area_list', $area_list);
            return view();
        }

    }

    // 删除
    public function delete()
    {
        $param = get_params();
        $Model = UnitModel::find($param['id']);
        $Model->delete();
        return to_assign();

    }

    //导入
    public function import(){
        // 获取表单上传文件
        $file[]= request()->file('file');
        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            //$objPHPExcel = $objReader->load('./storage/202209/d11544d20b3ca1c1a5f8ce799c3b2433.xlsx');
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }
            $data = [];

            for ($j = 1; $j <= $highestRow; $j++) {
                $title = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                if(empty($title)){
                    continue;
                }
                $data[$j - 2] = [
                    'title' => $title,
                    'uid' => $this->uid,
                    'did' => $this->did,
                    'create_time' => time()
                ];

            }

            // 批量添加数据
            if ((new BusinessTypeOneModel())->saveAll($data)) {
                return to_assign(0, '导入成功');
            }
            else{
                return to_assign(1, '导入失败，请检查excel文件再试');
            }
        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

}
